package org.ccay.manage.i18n.service.impl;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.excel.importer.IExcelImportContext;
import org.ccay.excel.importer.service.IExcelDataConsumer;
import org.ccay.i18n.I18nVO;
import org.ccay.i18n.service.ReloadableResourceBundle;
import org.ccay.manage.i18n.dao.II18nManageDao;

@Named("IExcelDataConsumer.i18nDataConsumer")
public class I18nImportConsumer implements IExcelDataConsumer {
	/**
	 * TRUE 的字符串表示形式
	 */
	public static final String IMPORT_TYPE = "noUpdate";

	@Inject
	private II18nManageDao i18nDao;
	
	@Inject
	ReloadableResourceBundle bundle;

	public void begin(IExcelImportContext context) throws ApplicationException {
	}

	@SuppressWarnings("unchecked")
	public int useBatchData(List<?> data, IExcelImportContext context) throws ApplicationException {
		/**
		 * 如果传递的数据是空的 直接返回0
		 */
		if (null == data || data.isEmpty()) {
			return 0;
		}
		List<I18nVO> i18nVOList = (List<I18nVO>) data;
		// 数据字段是否没有开启当前消; 只插入不更新
		String importType = context.getRequest().getParameters().get("importType");
		
		for(I18nVO vo: i18nVOList){
			I18nVO dbVO = i18nDao.findI18n(vo);
			if(dbVO == null){
				i18nDao.createI18n(vo);
			}else if(!IMPORT_TYPE.equals(importType)){
				vo.fillVirtualId();
				i18nDao.updateI18n(vo);
			}
		}
		
		return data.size();
	}

	public void fail(IExcelImportContext context) throws ApplicationException {
		
	}

	public void end(IExcelImportContext context) throws ApplicationException {
		if(context.getImportedCount() > 0){
			bundle.reload();
		}
	}

}
